package com.yksj.healthtalk.ui.salon;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.universalimageloader.core.DefaultConfigurationFactory;
import org.universalimageloader.core.DisplayImageOptions;
import org.universalimageloader.core.ImageLoader;
import org.universalimageloader.core.display.RoundedBitmapDisplayer;
import org.universalimageloader.utils.StorageUtils;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.adapter.CheckboxListAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.CheckBoxListFragment;
import com.yksj.healthtalk.comm.CheckBoxListFragment.onSeachPerson;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartControlClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.PopWindowUtil;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 
 * 组成员添加
 * 
 * @author jack_tang
 * 
 */
public class SalonSpecialPeoplsMenberAddActivity extends BaseFragmentActivity
		implements OnClickListener{

	String tabTag = "tab1";
	CheckBoxListFragment mBoxListFragment;// 多美号搜索
	EditText mEditText;
	EditText mEditText2;
	FragmentTabHost mTabHost;

	public String Special_Group_ID;// 按门票 组id
	public String Service_Group_ID;// 按服务 组id
	String groudId;// 群id
	

	@Override
	protected void onCreate(Bundle saveBundle) {
		super.onCreate(saveBundle);
		setContentView(R.layout.salon_special_peoples_menber_add_layout);

		if (saveBundle != null) {
			Special_Group_ID = saveBundle.getString("Special_Group_ID");
			Service_Group_ID = saveBundle.getString("Service_Group_ID");
			tabTag = saveBundle.getString("tabTag");
			groudId = saveBundle.getString("groupid");
		} else {
			Special_Group_ID = getIntent().getStringExtra("Special_Group_ID");
			Service_Group_ID = getIntent().getStringExtra("Service_Group_ID");
			groudId = getIntent().getStringExtra("groupid");
		}

		initUI();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("tabTag", tabTag);
		outState.putString("groupid", groudId);
		outState.putString("Special_Group_ID", Special_Group_ID);
		outState.putString("Service_Group_ID", Service_Group_ID);
	}

	private void initUI() {
		initTitle();
		titleTextV.setText("添加成员");
		setBackBtn("返回", this);
		setRightBtnYellowBg("确定", this);

		mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
	
		TabSpec mSpec = mTabHost.newTabSpec("tab1");
		Button button = new Button(this);
		button.setGravity(Gravity.CENTER);
		button.setText("按昵称多美号搜索");
		ColorStateList colorStateList = null;
		try {
			button.setTextColor(colorStateList = ColorStateList.createFromXml(
					getResources(),getResources().getXml(R.color.tab_color_selector)));
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		button.setBackgroundResource(R.drawable.dtab_left_normal_bg);
		mSpec.setIndicator(button);
		mTabHost.addTab(mSpec, CheckBoxListFragment.class, null);

		mSpec = mTabHost.newTabSpec("tab2");
		button = new Button(this);
		button.setGravity(Gravity.CENTER);
		button.setText("按分组搜索");
		button.setTextColor(colorStateList);
		button.setBackgroundResource(R.drawable.dtab_right_normal_bg);
		mSpec.setIndicator(button);
		Bundle bundle = new Bundle();
		bundle.putString("groudId", groudId);
		mTabHost.addTab(mSpec, GroupListFragment.class, bundle);
		mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String arg0) {
				tabTag = arg0;
			}
		});
		mTabHost.setCurrentTabByTag(tabTag);
	}

	@Override
	public void onClick(View v) {
		if (mBoxListFragment == null) {
			mBoxListFragment = (CheckBoxListFragment) getSupportFragmentManager().findFragmentByTag("tab1");
		}
		
		if("seach".equals(v.getTag())){//搜索
			TextView view=(TextView) v;
			onSearchByName(view.getText().toString());
		}
		
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.title_right2:// 添加人群
			addMenberNote(v);
			break;
		// 跳过
		case R.id.note_jump:
			// 之后按此执行
			if (mNoteCheck.isChecked()) {
				if (mNoteWindow.isShowing()) {
					mNoteWindow.dismiss();
				}
				onAddMenber();
				return;
			}
			++noteIndex;// 索引添加,显示下一个
			onUpdateNote();
			break;
		// 移动
		case R.id.note_move:
			// 执行移动,从非需要移动列表中删除
			mBoxListFragment.mAdapter.mOtherArray.remove(noteIndex);
			// 之后按此执行
			if (mNoteCheck.isChecked()) {
				if (mNoteWindow.isShowing()) {
					mNoteWindow.dismiss();
				}
				int size = mBoxListFragment.mAdapter.mOtherArray.size();
				JSONArray array = new JSONArray();
				for (int i = noteIndex; noteIndex < size; i++) {
					array.add(mBoxListFragment.mAdapter.mOtherArray.get(i));
				}
				mBoxListFragment.mAdapter.mOtherArray.removeAll(array);
				onAddMenber();
				return;
			} else {
				onUpdateNote();// 显示下一个
			}
			break;
		case R.id.note_cancel:
			if (mNoteWindow.isShowing()) {
				mNoteWindow.dismiss();
			}
			noteIndex = 0;
			break;
		}
	}

	private void onAddMenber() {
		CheckboxListAdapter mAdapter = mBoxListFragment.mAdapter;
		mAdapter.mChoosedArray.removeAll(mAdapter.mOtherArray);
		if (Special_Group_ID == null) {
			// 按服务添加
			onAddByServiceId();
		} else {
			// 按群添加
			onAddByGroupId();
		}
	}

	/**
	 * 添加提示
	 */
	private void addMenberNote(View v) {
		if (mNoteWindow != null && mNoteWindow.isShowing()) {
			mNoteWindow.dismiss();
			return;
		}
		// 当前要添加的成员不在其他分组的时候不需要提示移动分组,直接添加
		if (mBoxListFragment.mAdapter.mOtherArray.size() == 0) {
			onAddMenber();
			return;
		} else {
			showAddNoteWindow(v);
		}
	}

	// 添加提示
	CheckBox mNoteCheck;// 之后所有按选择执行
	TextView mNoteTxt;
	PopupWindow mNoteWindow;
	String note;
	int noteIndex = 0;

	/**
	 * 显示添加提示框
	 */
	private void showAddNoteWindow(View view) {
		note = getString(R.string.note_menber_add);
		View view2 = getLayoutInflater().inflate(
				R.layout.window_grou_menber_add, null);
		view2.findViewById(R.id.note_cancel).setOnClickListener(this);
		mNoteCheck = (CheckBox) view2.findViewById(R.id.note_check);
		view2.findViewById(R.id.note_jump).setOnClickListener(this);
		view2.findViewById(R.id.note_move).setOnClickListener(this);
		mNoteTxt = (TextView) view2.findViewById(R.id.note_txt);
		mNoteWindow = new PopupWindow(view2, LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);
		PopWindowUtil.setWindow(mNoteWindow);
		mNoteWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
		noteIndex = 0;
		onUpdateNote();
	}

	/**
	 * 更新提示
	 */
	private void onUpdateNote() {
		// 已经循环到最后一个
		if (mBoxListFragment.mAdapter.mOtherArray.size() <= noteIndex) {
			mNoteWindow.dismiss();
			onAddMenber();
		} else {
			JSONObject jsonObject = mBoxListFragment.mAdapter.mOtherArray
					.getJSONObject(noteIndex);
			String name = jsonObject.getString("display_name");
			mNoteTxt.setText(String.format(note, name));
		}
	}

	/**
	 * 按群门票添加特殊收费人群
	 */
	private void onAddByGroupId() {
		if ("tab1".equals(tabTag)) {// 按名称搜索添加
			final JSONArray array = mBoxListFragment.mAdapter.getChooseMap();
			final int size = array.size();
			if (size == 0)return;
			JSONArray jsonArray = new JSONArray();
			for (int i = 0; i < size; i++) {
				String id = array.getJSONObject(i).getString("CUSTOMER_ID");
				String groupid = array.getJSONObject(i).getString("SPECIAL_GROUP_ID");
				if (groupid == null || Special_Group_ID != groupid) {
					jsonArray.add(id);
				}
			}
			if (jsonArray.size() == 0)
				return;
			
			if(jsonArray.contains(SmartControlClient.getControlClient().getUserId())){
				
			}
			
			RequestParams params = new RequestParams();
			params.put("customerIds", jsonArray.toJSONString());
			
			params.put("specialGroupId", Special_Group_ID);
			params.put("type", "addSalonSpecialPriceGroupMember");
			HttpRestClient.doHttpSalonSpecialPriceGroupSet(params,
					new JsonsfHttpResponseHandler(this) {

						@Override
						public void onSuccess(int statusCode,
								JSONObject response) {
							if (response.containsKey("error_message")) {
								ToastUtil.showShort(response.getString("error_message"));
							} else {
								ToastUtil.showShort("添加成功");
							}
						}
					});
		}
	}

	/**
	 * 按服务类型添加
	 */
	private void onAddByServiceId() {
		// Type=addSpecialPriceGroupMember
		// CUSTOMER_ID 客户id
		// SPECIAL_GROUP_ID 服务特殊收费人群ID
		// SERVICE_ITEM_ID 医生服务项目ID
		// PARAME 添加的客户id，用放在数组里用json打包发过来
		// CUSTOMERGROUPID 组id
		if ("tab1".equals(tabTag)) {
			final JSONArray array = mBoxListFragment.mAdapter.getChooseMap();
			final int size = array.size();
			if (size == 0)
				return;
			JSONArray jsonArray = new JSONArray();
			for (int i = 0; i < size; i++) {
				String id = array.getJSONObject(i).getString("CUSTOMER_ID");
				String groupid = array.getJSONObject(i).getString("SPECIAL_GROUP_ID");
				if (Service_Group_ID != null && Service_Group_ID != groupid) {
					jsonArray.add(id);
				}
			}
			if (jsonArray.size() == 0)
				return;
			RequestParams params = new RequestParams();
			params.put("CUSTOMER_ID", SmartFoxClient.getLoginUserId());
			params.put("SPECIAL_GROUP_ID", Service_Group_ID);
			params.put("Type", "addSpecialPriceGroupMember");
			// params.put("CUSTOMERGROUPID","");
			params.put("SERVICE_ITEM_ID",
					getIntent().getStringExtra("SERVICE_ITEM_ID"));
			params.put("PARAME", jsonArray.toJSONString());
			HttpRestClient.doHttpServiceSetServletRJ320(params,
					new JsonsfHttpResponseHandler(this) {

						@Override
						public void onSuccess(int statusCode,
								JSONObject response) {
							if (response.containsKey("error_message")) {
								ToastUtil.showShort(response.getString("error_message"));
							} else {
								ToastUtil.showShort("添加成功");
							}
						}

					});
		} else {

		}
	}

	/**
	 * 查询名字或者多美号
	 * @param name
	 */
	private void onSearchByName(String name) {
		//按服务
		if(Service_Group_ID != null){
			RequestParams params = new RequestParams();
			params.put("account", name);
			params.put("customerId", SmartFoxClient.getLoginUserId());
			params.put("serviceItemId", getIntent().getStringExtra("SERVICE_ITEM_ID"));
			HttpRestClient.doHttpFindFriendsByNicknameOrAccount(params,
					new JsonsfHttpResponseHandler(this) {
						@Override
						public void onSuccess(int statusCode, JSONArray response) {
							mBoxListFragment.mAdapter.onDataChange(response);
						}
					});
		//按群	
		}else{
			RequestParams params = new RequestParams();
			params.put("account", name);
			params.put("customerId", SmartFoxClient.getLoginUserId());
			params.put("type", "findFriendsByNicknameOrAccount");
			params.put("groupId", groudId);
			HttpRestClient.doHttpSalonSpecialPriceGroupSet(params,
					new JsonsfHttpResponseHandler(this) {
						@Override
						public void onSuccess(int statusCode, JSONArray response) {
							mBoxListFragment.mAdapter.onDataChange(response);
						}
					});
		}
	}

	/**
	 * 按分组列表
	 * 
	 * @author zhao
	 */
	public static class GroupListFragment extends Fragment implements
			OnItemClickListener {
		PullToRefreshListView mListView;
		public GroupListAdapter mAdapter;

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			mAdapter = new GroupListAdapter(
					getLayoutInflater(savedInstanceState),getActivity());
		}

		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View view = inflater.inflate(R.layout.group_list_layout, null);
			mListView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_listview);
			mListView.setOnItemClickListener(this);
			mListView.getRefreshableView().addFooterView(inflater.inflate(R.layout.line_layout, null));
			mListView.getRefreshableView().setFooterDividersEnabled(false);
			return view;
		}

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			mListView.setAdapter(mAdapter);
			onQueryGroup();
		}

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			String groudId = getArguments().getString("groudId");
			JSONObject jsonObject = mAdapter.getItem(--position);
			Intent intent = getActivity().getIntent();
			intent.setClass(getActivity(),
					SalonSpecialPeoplsMenberAddByGroupActivity.class);
			intent.putExtra("groudId", groudId);
			intent.putExtra("json", jsonObject.toJSONString());
			startActivity(intent);
		}

		/**
		 * 按分组查询收费人群分组列表
		 */
		private void onQueryGroup() {
			RequestParams params = new RequestParams();
			params.put("CUSTOMER_ID", SmartFoxClient.getLoginUserId());
			params.put("Type", "queryGongge");
			HttpRestClient.doHttpServiceSetServlet320(params,
					new JsonsfHttpResponseHandler(getActivity()) {
						@Override
						public void onSuccess(int statusCode, JSONArray response) {
							mAdapter.onDataChange(response);
						}
					});
		}
	}

	/**
	 * 分组列表
	 * 
	 * @author zhao
	 * 
	 */
	static class GroupListAdapter extends BaseAdapter {
		JSONArray mArray = new JSONArray();
		LayoutInflater mInflater;
		private final ImageLoader mImageLoader;
		final List<String> mheaderList = new ArrayList<String>();

		DisplayImageOptions imageOptions; 
//		createUnknowNineHeaderDisplayImageOptions
		public GroupListAdapter(LayoutInflater inflater,Context context) {
			this.mInflater = inflater;
			this.mImageLoader = ImageLoader.getInstance();
			imageOptions = createUnknowHeaderDisplayImageOptions(context);
		}

		DisplayImageOptions createUnknowHeaderDisplayImageOptions(Context context){
			DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder(context)
			.showStubImage(R.drawable.default_jiugong_icon)
			.showImageForEmptyUri(R.drawable.default_jiugong_icon)
			.bitmapConfig(Bitmap.Config.RGB_565)
			.cacheOnDisc(new File(StorageUtils.getHeadersPath()))
			.cacheInMemory()
			.displayer(new RoundedBitmapDisplayer(5))
			.build();
			return displayImageOptions;
		}
		
		public void onDataChange(JSONArray jsonArray) {
			this.mArray = jsonArray;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return mArray.size();
		}

		@Override
		public boolean isEmpty() {
			return false;
		}

		@Override
		public JSONObject getItem(int position) {
			return mArray.getJSONObject(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder viewHolder;
			final JSONObject object = getItem(position);
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.special_group_list_item, null);
				viewHolder.headerImageV = (ImageView) convertView.findViewById(R.id.head_image);
				viewHolder.nameTextV = (TextView) convertView.findViewById(R.id.name);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			int size = 0;
			try {
				size = object.getInteger("CUSTOMERCOUNT");
			} catch (Exception e) {
			}
			viewHolder.nameTextV.setText(object.getString("PATIENT_GROUP")
					+ "(" + size + "人)");
			Object object2 = object.get("ICON");
			String[] strs = null;
			if (object2 instanceof String) {
				try {
					JSONArray array = JSON.parseArray((String) object2);
					strs = new String[array.size()];
					array.toArray(strs);
					object.put("ICON", strs);
				} catch (Exception e) {
				}
			} else {
				strs = (String[]) object.get("ICON");
			}
			mImageLoader.displayImage(strs, viewHolder.headerImageV, imageOptions);
			return convertView;
		}
	}

	private static class ViewHolder {
		ImageView headerImageV;
		TextView nameTextV;
	}

//	@Override
//	public void seach(String str) {
//		onSearchByName(str);
//	}
}
